package com.lgc.webtest.configuration.dataSource;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据源切换
 */
public class DBContextHolder {
    private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();
    private static final AtomicInteger counter = new AtomicInteger(-1);
    public static void set(DBTypeEnum dbType) {
        contextHolder.set(dbType);
    }
    public static DBTypeEnum get() {
        return contextHolder.get();
    }

    /**
     * 支付库写库
     */
    public static void paymentMaster() {
        set(DBTypeEnum.PAYMENT_WRITE);
        System.out.println("切换到master");
    }

    /**
     * 商户库写库
     */
    public static void partnerMaster() {
        set(DBTypeEnum.PARTNER_WRITE);
        System.out.println("切换到master");
    }

    /**
     * 支付库写库
     */
    public static void paymentSlave() {
        // 轮询
        int index = counter.getAndIncrement() % 1;
        if (counter.get() > 9999) {
            counter.set(-1);
        }
        if (index == 0) {
            set(DBTypeEnum.PAYMENT_READ);
            System.out.println("切换到slave1");
        }else {
            set(DBTypeEnum.PAYMENT_READ);
            System.out.println("切换到slave2");
        }
    }

    /**
     * 商户库读库
     */
    public static void partnerSlave() {
        // 轮询
        int index = counter.getAndIncrement() % 2;
        if (counter.get() > 9999) {
            counter.set(-1);
        }
        if (index == 0) {
            set(DBTypeEnum.PARTNER_READ);
            System.out.println("切换到slave1");
        }else {
            set(DBTypeEnum.PARTNER_READ);
            System.out.println("切换到slave2");
        }
    }
}

